package com.itheima.auth;

import com.itheima.utils.JwtTokenUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
/**
 * 校验token的过滤器
 * */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private static final String TOKEN_HEADER = "token";

    private Map<String, Map<String,String>> userMap = new HashMap<>();

    private boolean inited;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(TOKEN_HEADER);
        try {
            if(token != null){
                //解密token
                //数据库用户查询
                String username = JwtTokenUtil.parseToken(token);
                initUser();
                Map<String,String> userInfo = userMap.get(username);
                User user = null;
                if(userInfo != null){
                    user = new User(username,userInfo.get("pwd"),AuthorityUtils.commaSeparatedStringToAuthorityList(userInfo.get("auth")));
                }
                //身份信息处理
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                //把我们已经认证好的身份信息往下传递
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }finally {
            //过滤器放行
            filterChain.doFilter(request, response);
        }
    }

    private void initUser(){
        if(inited == false){
            //构建用户信息同时还有用户对应的权限
            Map<String,String> aaaUser = new HashMap<>();
            aaaUser.put("pwd",passwordEncoder.encode("aaa"));
            aaaUser.put("auth","ROLE_aaa,ROLE_bbb");
            userMap.put("aaa",aaaUser);

            Map<String,String> bbbUser = new HashMap<>();
            bbbUser.put("pwd",passwordEncoder.encode("bbb"));
            bbbUser.put("auth","ROLE_bbb");
            userMap.put("bbb",bbbUser);
            inited = true;
        }
    }

}
